<template>
	<div>
		<ProTable ref="proTable" title="货品入库" :columns="columns" :request-api="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" v-auth="'product:warehouse:import:invoke'" @click="openImport()"> 导入货品 </el-button>
				</div>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" link v-auth-all="['product:warehouse:edit:invoke', 'product:warehouse:details:invoke']" @click="openImport(row)">
					编辑
				</el-button>
				<el-divider direction="vertical" v-auth-all="['product:warehouse:edit:invoke', 'product:warehouse:details:invoke']" />
				<el-button type="primary" link v-auth="'product:warehouse:delete:invoke'" @click="onDelete(row)"> 删除 </el-button>
			</template>
		</ProTable>
		<Import :visible="importVisible" :row="updateRow" @handleClose="closeImport"></Import>
	</div>
</template>

<script setup lang="tsx" name="goodsWarehousing">
import { onMounted, ref, reactive, computed } from 'vue';
import dayjs from 'dayjs';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchWarehousingList, fetchWarehousingEnums, fetchDelWarehousing } from '/@/api/goods';
import Import from './dialog/import.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fenToYuan } from '/@/utils/commonFunction';

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'id',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
	}
	delete data.paramValue;
	delete data.paramCode;

	return fetchWarehousingList(data);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '物料搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'id',
		label: '物料ID',
		minWidth: 160,
	},
	{
		prop: 'materialName',
		label: '物料名称',
		minWidth: 160,
	},
	{
		prop: 'materialCode',
		label: '物料编码',
		minWidth: 160,
	},
	{
		prop: 'brandName',
		label: '所属品牌',
		minWidth: 160,
	},
	{
		prop: 'productYear',
		label: '生产年份',
		minWidth: 160,
		search: { el: 'select', props: { placeholder: '请选择生产年份' } },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchWarehousingEnums('product').then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.map((v: any) => ({ label: v, value: v })),
					});
				});
			});
		},
		render: (scope) => {
			return scope.row.productYear;
		},
	},
	{
		prop: 'storeYear',
		label: '瓶储年份',
		minWidth: 160,
		search: { el: 'select', props: { placeholder: '请选择瓶储年份' } },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchWarehousingEnums('store').then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.map((v: any) => ({ label: v, value: v })),
					});
				});
			});
		},
		render: (scope) => {
			return scope.row.storeYear;
		},
	},
	{
		prop: 'inventory',
		label: '可售库存(件)',
		minWidth: 160,
	},
	{
		prop: 'presentInventory',
		label: '实际库存(瓶/盒)',
		minWidth: 160,
	},
	{
		prop: 'recommendedPrice',
		label: '建议售价',
		minWidth: 160,
		render: (scope) => {
			return fenToYuan(scope.row.recommendedPrice);
		},
	},
	{
		prop: 'costPrice',
		label: '成本价',
		minWidth: 160,
		render: (scope) => {
			return fenToYuan(scope.row.costPrice);
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'left' },
];

const searchArr = [
	{
		label: '物料ID',
		value: 'id',
	},
	{
		label: '物料编码',
		value: 'materialCode',
	},
	{
		label: '物料名称',
		value: 'materialName',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const importVisible = ref(false);
const updateRow = ref();

const openImport = (row?: any) => {
	if (row) {
		updateRow.value = row;
	} else {
		updateRow.value = null;
	}
	importVisible.value = true;
};

const closeImport = (bool: boolean) => {
	importVisible.value = false;
	updateRow.value = null;
	if (bool) {
		proTable.value?.getTableList();
	}
};

const onDelete = async (row: any) => {
	ElMessageBox.confirm('确认删除该货品?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelWarehousing({ id: row.id });
		if (res.code == 200) {
			ElMessage.success('删除成功');
			proTable.value?.getTableList();
		}
	});
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
